package loader {
	import away3d.events.AssetEvent;
	import away3d.loaders.Loader3D;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	/**
	 * 加载管理器
	 * @author yungzhu@gmail.com
	 * Morn UI：flash轻量级，高性能，可视化UI解决方案 https://code.google.com/p/morn/
	 */
	public class LoaderManager extends EventDispatcher {
		public static var instance:LoaderManager = new LoaderManager();
		private var _queue:Array = [];
		private var _isLoading:Boolean;
		private var _loader:Loader3D = new Loader3D();
		private var _urlRequest:URLRequest = new URLRequest();
		private var _loadInfo:Array;
		
		public function load(url:String,type:String, complete:Function = null, args:Array = null):void {
			_queue.push([url,type, complete, args]);
			checkNext();
		}
		
		private function checkNext():void {
			if (_isLoading) {
				return;
			}
			if (_queue.length > 0) {
				_isLoading = true;
				_loadInfo = _queue.shift();
				_urlRequest.url = _loadInfo[0];
				_loader.load(_urlRequest);
				_loader.addEventListener(AssetEvent.ASSET_COMPLETE, onLoaderAssetComplete);
			}else {
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		private function onLoaderAssetComplete(e:AssetEvent):void {
			var type:String = _loadInfo[1];
			if (e.asset.assetType == type) {
				var complete:Function = _loadInfo[2];
				var args:Array = _loadInfo[3];
				if (complete != null) {
					var handler:Function = complete;
					_loadInfo = null;
					handler.apply(null, args.concat([e.asset]));
				}
				_isLoading = false;
				checkNext();
			}
		}
	}
}